package com.jshcbd.mvp_kt_demo.utils

import android.annotation.SuppressLint
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by zzt
 * 2021/6/30
 */
object BirthdayToAgeUtil {
    private var birthday: String? = null
    private var ageStr: String? = null
    private var age = 0

    //出生年、月、日
    private var year = 0
    private var month = 0
    private var day = 0
    fun BirthdayToAge(birthday1: String?): String? {
        birthday = birthday1
        stringToInt(birthday, "yyyy-MM-dd")
        // 得到当前时间的年、月、日
        val cal = Calendar.getInstance()
        val yearNow = cal[Calendar.YEAR]
        val monthNow = cal[Calendar.MONTH] + 1
        val dayNow = cal[Calendar.DATE]
        //        Log.d("birth", "yearNow：" + yearNow);
//        Log.d("birth", "monthNow：" + monthNow);
//        Log.d("birth", "dayNow：" + dayNow);
        // 用当前年月日减去出生年月日
        val yearMinus = yearNow - year
        val monthMinus = monthNow - month
        val dayMinus = dayNow - day
        age = yearMinus // 先大致赋值
        if (yearMinus <= 0) {
            age = 0
            ageStr = age.toString() + "周岁啦！"
            return ageStr
        }
        if (monthMinus < 0) {
            age -= 1
        } else if (monthMinus == 0) {
            if (dayMinus < 0) {
                age -= 1
            }
        }
        ageStr = age.toString() + "周岁啦！"
        return ageStr
    }

    /**
     * String类型转换成date类型
     * strTime: 要转换的string类型的时间，
     * formatType: 要转换的格式yyyy-MM-dd HH:mm:ss
     * //yyyy年MM月dd日 HH时mm分ss秒，
     * strTime的时间格式必须要与formatType的时间格式相同
     */
    private fun stringToDate(strTime: String?, formatType: String): Date? {
//        Log.d("birth", "进入stringToDate");
        return try {
            val formatter = SimpleDateFormat(formatType)
            val date: Date = formatter.parse(strTime)
            date
        } catch (e: Exception) {
            null
        }
    }

    /**
     * String类型转换为long类型
     * .............................
     * strTime为要转换的String类型时间
     * formatType时间格式
     * formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
     * strTime的时间格式和formatType的时间格式必须相同
     */
    private fun stringToInt(strTime: String?, formatType: String) {
//        Log.d("birth", "进入stringToLong");
        try {
            //String类型转换为date类型
            val calendar = Calendar.getInstance()
            val date = stringToDate(strTime, formatType)
            calendar.time = date
            //            Log.d("birth", "调用stringToDate()获得的date：" + date);
            if (date == null) {
            } else {
                //date类型转成long类型
                year = calendar[Calendar.YEAR]
                month = calendar[Calendar.MONTH] + 1
                day = calendar[Calendar.DAY_OF_MONTH]
            }
        } catch (e: Exception) {
//            Log.d("birth", "Exception：" + e);
        }
    }
}